<template>
  <!-- Hide the custom cursor completely -->
  <div v-if="isCustomCursorEnabled" class="custom-cursor-container">
    <div
      class="cursor-sword"
      :style="{
        transform: `translate3d(${position.x}px, ${position.y}px, 0) rotate(45deg)`,
        opacity: isVisible ? 1 : 0,
        width: `${36 * cursorSize}px`,
        height: `${36 * cursorSize}px`,
        '--cursor-color': cursorColor
      }"
      :class="{ 'cursor-hover': isHovering }"
    >
      <!-- 钻石剑样式 -->
      <div class="sword-shape"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'

// Set to false to use system cursor instead of custom cursor
const isCustomCursorEnabled = ref(true)

const position = ref({ x: 0, y: 0 })
const actualPosition = ref({ x: 0, y: 0 }) // 实际鼠标位置
const isVisible = ref(false)
const isHovering = ref(false)
const customCursorColor = ref('')
const customCursorSize = ref(1)
let animationFrameId = null

// 从localStorage获取光标设置
const loadCursorSettings = () => {
  try {
    const savedSettings = localStorage.getItem('cursor_settings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      customCursorColor.value = settings.cursorColor || ''
      customCursorSize.value = settings.cursorSize || 1
    }
  } catch (error) {
    console.log('加载光标设置失败')
  }
}

// 计算光标颜色
const cursorColor = computed(() => {
  return customCursorColor.value || 'white'
})

// 计算光标大小
const cursorSize = computed(() => {
  return customCursorSize.value || 1
})

// 监听光标设置更新事件
const handleCursorSettingsUpdated = (event) => {
  if (event.detail) {
    if (event.detail.cursorColor) {
      customCursorColor.value = event.detail.cursorColor
    }
    if (event.detail.cursorSize) {
      customCursorSize.value = event.detail.cursorSize
    }
  } else {
    loadCursorSettings()
  }
}

// 使用requestAnimationFrame平滑光标移动
const smoothCursorMovement = () => {
  // 插值系数：0.3表示每帧移动实际位置和当前位置差距的30%，值越大越快但越不平滑
  const ease = 0.3
  
  // 计算当前位置和目标位置之间的差值
  const diffX = actualPosition.value.x - position.value.x
  const diffY = actualPosition.value.y - position.value.y
  
  // 更新位置，添加一点平滑过渡
  position.value.x += diffX * ease
  position.value.y += diffY * ease
  
  // 继续下一帧动画
  if (isCustomCursorEnabled.value) {
    animationFrameId = requestAnimationFrame(smoothCursorMovement)
  }
}

// 鼠标移动处理
const handleMouseMove = (e) => {
  if (!isCustomCursorEnabled.value) return;
  
  // 更新实际鼠标位置
  actualPosition.value = {
    x: e.clientX,
    y: e.clientY
  }
  
  // 确保光标可见
  isVisible.value = true
}

// 鼠标进入窗口
const handleMouseEnter = () => {
  if (!isCustomCursorEnabled.value) return;
  isVisible.value = true
}

// 鼠标离开窗口
const handleMouseLeave = () => {
  if (!isCustomCursorEnabled.value) return;
  isVisible.value = false
}

// 鼠标按下处理
const handleMouseDown = () => {
  if (!isCustomCursorEnabled.value) return;
  // 可以在这里添加鼠标按下的视觉效果
  isHovering.value = true
}

// 鼠标抬起处理
const handleMouseUp = () => {
  if (!isCustomCursorEnabled.value) return;
  // 恢复正常状态
  isHovering.value = false
}

// 鼠标悬停在可点击元素上
const handleElementHover = (e) => {
  if (!isCustomCursorEnabled.value) return;
  const target = e.target
  if (
    target.tagName.toLowerCase() === 'a' ||
    target.tagName.toLowerCase() === 'button' ||
    target.classList.contains('clickable') ||
    target.closest('.el-button') ||
    target.closest('a') ||
    target.closest('.clickable')
  ) {
    isHovering.value = true
  } else {
    isHovering.value = false
  }
}

// 隐藏系统光标
const hideSystemCursor = () => {
  if (!isCustomCursorEnabled.value) return;
  // 给html和body元素都添加cursor: none样式
  document.documentElement.style.cursor = 'none'
  document.body.style.cursor = 'none'
  
  // 给所有可点击元素添加自定义样式
  const clickableElements = document.querySelectorAll('a, button, .clickable, .el-button')
  clickableElements.forEach(el => {
    el.style.cursor = 'none'
  })
}

// 恢复系统光标（用于组件卸载时）
const restoreSystemCursor = () => {
  document.documentElement.style.cursor = ''
  document.body.style.cursor = ''
  
  const clickableElements = document.querySelectorAll('a, button, .clickable, .el-button')
  clickableElements.forEach(el => {
    el.style.cursor = ''
  })
}

// 生命周期钩子
onMounted(() => {
  console.log('CustomCursor组件已挂载')
  
  // 加载光标设置
  loadCursorSettings()
  
  // 添加事件监听器
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseenter', handleMouseEnter)
  document.addEventListener('mouseleave', handleMouseLeave)
  document.addEventListener('mousedown', handleMouseDown)
  document.addEventListener('mouseup', handleMouseUp)
  
  // 监听设置更新事件
  window.addEventListener('cursor-settings-updated', handleCursorSettingsUpdated)
  
  // 启动动画循环
  if (isCustomCursorEnabled.value) {
    animationFrameId = requestAnimationFrame(smoothCursorMovement)
    
    // 隐藏原生光标
    document.body.style.cursor = 'none'
    
    // 为所有可点击元素添加悬停检测
    const clickableElements = document.querySelectorAll('a, button, [role="button"], input, select, textarea, [tabindex]:not([tabindex="-1"])')
    clickableElements.forEach(el => {
      el.addEventListener('mouseenter', () => isHovering.value = true)
      el.addEventListener('mouseleave', () => isHovering.value = false)
    })
  }
})

onUnmounted(() => {
  console.log('CustomCursor组件已卸载')
  
  // 移除事件监听器
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseenter', handleMouseEnter)
  document.removeEventListener('mouseleave', handleMouseLeave)
  document.removeEventListener('mousedown', handleMouseDown)
  document.removeEventListener('mouseup', handleMouseUp)
  
  // 移除设置更新事件监听
  window.removeEventListener('cursor-settings-updated', handleCursorSettingsUpdated)
  
  // 取消动画帧
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
  
  // 恢复原生光标
  document.body.style.cursor = ''
  
  // 移除悬停检测
  const clickableElements = document.querySelectorAll('a, button, [role="button"], input, select, textarea, [tabindex]:not([tabindex="-1"])')
  clickableElements.forEach(el => {
    el.removeEventListener('mouseenter', () => isHovering.value = true)
    el.removeEventListener('mouseleave', () => isHovering.value = false)
  })
})
</script>

<style scoped>
.custom-cursor-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 9999;
  overflow: hidden;
}

.cursor-sword {
  position: absolute;
  width: 36px;
  height: 36px;
  transform-origin: center;
  transition: opacity 0.15s ease;
  pointer-events: none;
  will-change: transform;
  --cursor-color: white; /* 默认颜色 */
}

.sword-shape {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  clip-path: polygon(50% 0%, 40% 40%, 0% 50%, 40% 60%, 50% 100%, 60% 60%, 100% 50%, 60% 40%);
  background-color: var(--cursor-color);
  box-shadow: 0 0 8px var(--cursor-color);
  opacity: 0.7;
  transition: transform 0.1s ease, opacity 0.1s ease;
}

.cursor-hover .sword-shape {
  background-color: var(--cursor-color);
  box-shadow: 0 0 12px var(--cursor-color), 0 0 20px var(--cursor-color);
  opacity: 0.9;
  transform: scale(1.2) rotate(45deg);
}

/* 移动设备隐藏自定义光标 */
@media (max-width: 768px) {
  .custom-cursor-container {
    display: none;
  }
}
</style>

<style>
/* 全局样式：在自定义光标禁用时不应用 */
</style> 